package com.example.zyflutter.plugin

import com.example.zyflutter.StoreApiManager
import com.example.zyflutter.service.AppService
import com.example.zyflutter.service.BookStoreApiService
import com.example.zyflutter.utils.LogUtils
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

/**
 * 自定义的插件
 */
class MyPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
    private lateinit var channel: MethodChannel
    private lateinit var appService: AppService

    /**
     * 插件和调用者在同一个工程的时候，需要在FlutterActivity的configureFlutterEngine注册，该方法才会被回调
     */
    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        LogUtils.logE("MyPlugin", "onAttachedToEngine");
        channel = MethodChannel(binding.binaryMessenger, "my_first_plugin")
        channel.setMethodCallHandler(this)
        appService = AppService(binding.applicationContext)
        StoreApiManager.StoreApi.setup(binding.binaryMessenger, BookStoreApiService())
    }

    /**
     * 插件和调用者在同一个工程的时候，需要在FlutterActivity的configureFlutterEngine注册，该方法才会被回调
     */
    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        LogUtils.logE("MyPlugin", "onDetachedFromEngine");
        channel.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        LogUtils.logE("MyPlugin", "onMethodCall");
        val method = call.method
        if (method == "getPlatformVersion") {
            LogUtils.logE("MyPlugin onMethodCall getPlatformVersion")
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (method == "getAppList") {
            LogUtils.logE("MyPlugin onMethodCall getAppList appService.pkgList")
            val pkgList = appService.pkgList
            LogUtils.logE("MyPlugin onMethodCall getAppList List = ${pkgList.size}")
            result.success(pkgList)
        } else {
            LogUtils.logE("MyPlugin onMethodCall notImplemented")
            result.notImplemented()
        }
    }
}